package com.indsvr;

import com.google.gson.Gson;
import com.indsvr.entity.response.IndSvrRoot;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@EnableCaching
@Component
public class PermissionInterceptorConfig implements WebMvcConfigurer {

    @Value("${indsvr.token}")
    private String token;

    @Value("${indsvr.version}")
    private String version;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        InterceptorRegistration ir = registry.addInterceptor(new HandlerInterceptor() {
            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

                if (!(version.equals(request.getHeader("version"))) && !("web".equals(request.getHeader("version")))) {
                    response.setContentType("application/json;charset=UTF-8");
                    response.getWriter().write(new Gson().toJson(IndSvrRoot.versionDiscrepancy(version)));
                    response.getWriter().flush();
                    return false;
                }


                if (token==null||"".equals(token)) {
                    System.out.println("token authentication is not enabled.");
                    return true;
                }
                if (token.equals(request.getHeader("token"))) {
                    return true;
                }

                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().write(new Gson().toJson(IndSvrRoot.no("Token 认证失败")));
                response.getWriter().flush();
                return false;
            }
        });
        ir.addPathPatterns("/**");
        ir.excludePathPatterns("/");
        ir.excludePathPatterns("/index.html");
        ir.excludePathPatterns("/chrome/**");
        ir.excludePathPatterns("/plugin");
    }





}
